/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export function csEtree(a, ata) {
  // check inputs
  if (!a) {
    return null;
  } // a arrays


  var aindex = a._index;
  var aptr = a._ptr;
  var asize = a._size; // rows & columns

  var m = asize[0];
  var n = asize[1]; // allocate result

  var parent = []; // (n)
  // allocate workspace

  var w = []; // (n + (ata ? m : 0))

  var ancestor = 0; // first n entries in w

  var prev = n; // last m entries (ata = true)

  var i, inext; // check we are calculating A'A

  if (ata) {
    // initialize workspace
    for (i = 0; i < m; i++) {
      w[prev + i] = -1;
    }
  } // loop columns


  for (var k = 0; k < n; k++) {
    // node k has no parent yet
    parent[k] = -1; // nor does k have an ancestor

    w[ancestor + k] = -1; // values in column k

    for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
      // row
      var r = aindex[p]; // node

      i = ata ? w[prev + r] : r; // traverse from i to k

      for (; i !== -1 && i < k; i = inext) {
        // inext = ancestor of i
        inext = w[ancestor + i]; // path compression

        w[ancestor + i] = k; // check no anc., parent is k

        if (inext === -1) {
          parent[i] = k;
        }
      }

      if (ata) {
        w[prev + r] = k;
      }
    }
  }

  return parent;
}